﻿using System;
using System.Collections.Generic;
using System.Linq;
using DataBaseLayer.Abstractions.Interfaces.Services;
using DataBaseLayer.Dto;
using DataBaseLayer.Extensions;

namespace DataBaseLayer.Services
{
	public class NewsService : INewsService
	{
		#region Variables

		private readonly churchDataBase _dataBase;

		#endregion

		#region Constructors

		public NewsService(churchDataBase dataBase)
		{
			if (dataBase == null)
				throw new ArgumentNullException(string.Format("data base"));

			_dataBase = dataBase;
		}

		#endregion

		#region INewsService Members

		public int GetCountNews()
		{
			return _dataBase.News.Count();
		}

		public IEnumerable<NewsData> GetNewsByPageNumber(int pageNumber, int countNews)
		{
			var result = _dataBase.News.OrderByDescending(n => n.NewsId).Skip(pageNumber*countNews).Take(countNews).AsEnumerable().Select(n =>
			{
				var news = n.ToDTO();
				Image image = null;
				if (n.Gallery != null && n.Gallery.Images != null && n.Gallery.Images.Any())
					image = n.Gallery.Images.FirstOrDefault(i => i.IsDefault) ?? n.Gallery.Images.FirstOrDefault();
				news.ImageUrl = image != null ? image.Url : string.Empty;
				return news;
			}).ToList();

			return result;
		}

		public NewsData GetNewsById(int newsId, int countNewsOnPage)
		{
			var news = _dataBase.News.SingleOrDefault(n => n.NewsId == newsId);
			if (news == null) return null;
			Image image = null;
			if (news.Gallery != null && news.Gallery.Images != null && news.Gallery.Images.Any())
				image = news.Gallery.Images.FirstOrDefault();
			var result = news.ToDTO();
			result.ImageUrl = image != null ? image.Url : string.Empty;
			result.PageNumber = _dataBase.News.Count(n => n.NewsId > result.NewsId)/countNewsOnPage + 1;
			return result;
		}

		public IEnumerable<NewsData> GetNews()
		{
			return _dataBase.News.ToDTOs();
		}

		public void UpdateNews(NewsData news)
		{
			if (news != null)
			{
				var oldNews = _dataBase.News.SingleOrDefault(n => n.NewsId == news.NewsId);
				if (oldNews != null)
				{
					oldNews.Header = news.Header;
					oldNews.Description = news.Description;
					oldNews.GalleryId = news.GalleryId;
					_dataBase.SaveChanges();
				}
			}
		}

		public void CreateNews(NewsData news)
		{
			if (news != null)
			{
				var newNews = new News
				{
					Header = news.Header,
					Description = news.Description,
					GalleryId = news.GalleryId
				};
				_dataBase.News.Add(newNews);
				_dataBase.SaveChanges();
			}
		}

		public void DeleteNewsById(int id)
		{
			var newsForDel = _dataBase.News.SingleOrDefault(n => n.NewsId == id);
			if (newsForDel != null)
			{
				_dataBase.News.Remove(newsForDel);
				_dataBase.SaveChanges();
			}
		}

		#endregion
	}
}
